<template>
  <div class="app-container">
    <!-- 面包屑导航（若依标准组件） -->
    <breadcrumb/>
    <!-- 搜索区域（若依行内表单风格） -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <!-- 采购入库单号查询 -->
      <el-form-item label="采购入库单号" prop="receiptsNo">
        <el-input
          v-model="queryParams.receiptsNo"
          placeholder="请输入采购入库单号"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 仓库查询 -->
      <el-form-item label="仓库" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库编号/名称"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 供应商查询 -->
      <el-form-item label="供应商" prop="supplierName">
        <el-input
          v-model="queryParams.supplierName"
          placeholder="请输入供应商编号/名称"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 审核状态（若依字典翻译） -->
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select
          v-model="queryParams.auditStatus"
          placeholder="请选择审核状态"
          clearable
          size="mini"
        >
          <!-- 修复：将 dict.type.audit_status 改为 dict.audit_status -->
          <el-option
            v-for="item in dict.audit_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 审核人查询 -->
      <el-form-item label="审核人" prop="auditor">
        <el-input
          v-model="queryParams.auditor"
          placeholder="请输入审核人查询"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 操作时间查询（若依日期范围组件） -->
      <el-form-item label="操作时间" prop="operateTimeRange">
        <el-date-picker
          v-model="queryParams.operateTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="mini"
        />
      </el-form-item>


      <!-- 审核时间查询 -->
      <el-form-item label="审核时间" prop="auditTimeRange">
        <el-date-picker
          v-model="queryParams.auditTimeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="mini"
        />
      </el-form-item>

      <!-- 搜索/重置按钮（若依标准样式） -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格（若依标准表格样式） -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      :header-cell-style="{background: '#f5f7fa', color: '#606266'}"
      style="width: 100%"
    >
      <el-table-column label="序号" type="index" width="50" align="center"/>
      <el-table-column label="采购入库单号" prop="inboundNo" align="center" width="180"/>
      <el-table-column label="仓库编号" prop="warehouseId" align="center" width="100"/>
      <el-table-column label="仓库名称" prop="warehouseName" align="center" width="120"/>
      <el-table-column label="供应商编号" prop="supplierId" align="center" width="100"/>
      <el-table-column label="供应商名称" prop="supplierName" align="center" width="120"/>
      <el-table-column label="商品种类数" prop="quantity" align="center" width="80"/>
      <el-table-column label="采购结算总金额(元)" prop="actualPrice" align="center" width="120">
      </el-table-column>
      <el-table-column label="审核状态" prop="auditStatus" align="center" width="100">
        <template slot-scope="scope">
          <el-tag :type="getAuditTagType(scope.row.auditStatus)">
            {{ getAuditTagLabel(scope.row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" prop="createTime" align="center" width="160"/>
      <el-table-column label="审核人Id" prop="approver" align="center" width="100"/>
      <el-table-column label="审核时间" prop="approveTime" align="center" width="160"/>
      <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 查看按钮（所有角色可见） -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件（若依标准分页） -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />



    <!-- 查看采购入库单弹窗（新增完整代码） -->
    <el-dialog :title="title" :visible.sync="openView" width="500px" append-to-body>
      <el-form ref="viewForm" :model="viewForm" label-width="120px">
        <el-form-item label="采购入库单号" prop="inboundNo">
          <el-input v-model="viewForm.inboundNo" disabled/>
        </el-form-item>
        <el-form-item label="仓库编号" prop="warehouseId">
          <el-input v-model="viewForm.warehouseId" disabled/>
        </el-form-item>
        <el-form-item label="仓库名称" prop="warehouseName">
          <el-input v-model="viewForm.warehouseName" disabled/>
        </el-form-item>
        <el-form-item label="供应商编号" prop="supplierId">
          <el-input v-model="viewForm.supplierId" disabled/>
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input v-model="viewForm.supplierName" disabled/>
        </el-form-item>
        <el-form-item label="商品种类数" prop="quantity">
          <el-input v-model="viewForm.quantity" disabled/>
        </el-form-item>
        <el-form-item label="采购结算总金额(元)" prop="actualPrice">
          <el-input v-model="viewForm.actualPrice" disabled/>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus">
          <el-tag :type="getAuditTagType(viewForm.auditStatus)">
            {{ getAuditTagLabel(viewForm.auditStatus) }}
          </el-tag>
        </el-form-item>
        <el-form-item label="操作时间" prop="createTime">
          <el-input v-model="viewForm.createTime" disabled/>
        </el-form-item>
        <el-form-item label="审核人ID" prop="approver">
          <el-input v-model="viewForm.approver" disabled/>
        </el-form-item>
        <el-form-item label="审核时间" prop="approveTime">
          <el-input v-model="viewForm.approveTime" disabled/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关闭</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  listReceipts,
  deleteReceipts,
  submitReceipts,
  getReceipts,
  addReceipts,
  updateReceipts,
  getReceiptsOperationRecords
} from "@/api/erp/receipts";
import {getDicts} from "@/api/system/dict/data";
import {hasPermi} from "@/utils/permission";
import Breadcrumb from "@/components/Breadcrumb/index.vue";
import Pagination from "@/components/Pagination/index.vue";

export default {
  name: "PurchaseReceipts",
  components: {Breadcrumb, Pagination},
  data() {
    return {
      // 加载状态
      loading: false,
      // 表格数据
      tableData: [],
      // 总条数
      total: 0,
      // 查询参数（仅保留分页和搜索相关）
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        receiptsNo: "",
        warehouseName: "",
        supplierName: "",
        auditStatus: "",
        operateTimeRange: [],
        creator: "",
        auditTimeRange: [],
        auditor: ""
      },
      // 字典数据（审核状态）
      dict: {
        audit_status: []
      },
      // 弹窗控制（独立声明）
      openAddOrEdit: false,
      openView: false,
      openDelete: false,
      openSubmit: false,
      // 表单数据（独立声明）
      form: {},
      addOrEditTitle: "新增采购入库单",
      addOrEditForm: {
        id: null,
        inboundNo: "",
        warehouseId: null,
        warehouseName: "",
        supplierId: null,
        supplierName: "",
        auditStatus: "0",
        actualPrice: 0,
        quantity: 0,
        approver: ""
      },
      addOrEditRules: {
        warehouseId: [          // 修改为验证ID
          {required: true, message: "请选择仓库", trigger: "blur"}
        ],
        supplierId: [           // 修改为验证ID
          {required: true, message: "请选择供应商", trigger: "blur"}
        ],
      },
      viewForm: {},
      // 商品选择相关
      goodsOptions: [],
      selectedGoods: [],
      operationRecords: [],
      disabledStatus: false,
      // 当前用户信息（新增声明）
      currentUser: null,
      // 弹窗标题
      title: ""
    };
  },
  created() {
    // 初始化：加载字典 + 加载列表数据
    this.getDicts("audit_status").then(() => {
      // 新增：获取当前用户信息，用于数据级权限过滤
      this.getCurrentUser().then(() => {
        this.getList();
      });
    });
  },
  methods: {
    // 加载字典数据（若依工具函数）
    getDicts(dictType) {
      return new Promise((resolve) => {
        getDicts(dictType).then((response) => {
          this.dict[dictType] = response.data;
          resolve();
        });
      });
    },
    // 获取审核状态标签类型（warning/info/success/danger）
    getAuditTagType(status) {
      switch (status) {
        case '0':
          return 'warning';
        case '1':
          return 'info';
        case '2':
          return 'success';
        default:
          return 'danger'; // 包含状态3（审核拒绝）
      }
    },
    // 获取审核状态标签文本
    getAuditTagLabel(status) {
      // 先判断字典是否存在，避免 find 报错
      if (!this.dict.audit_status || this.dict.audit_status.length === 0) {
        return '未知状态';
      }
      // 只调用一次 find，结果存在则返回 label，否则返回未知
      const statusItem = this.dict.audit_status.find(item => item.value === status);
      return statusItem ? statusItem.label : '未知状态';
    },
    // 获取当前用户信息
    getCurrentUser() {
      return new Promise((resolve, reject) => {
        // 1. 确认 action 路径正确：user/getInfo（与模块命名空间、action 名一致）
        this.$store.dispatch('GetInfo')
          .then(res => {
            this.currentUser = res;
            resolve(res); // 成功时返回用户信息
          })
          .catch(error => {
            // 2. 捕获异常（避免控制台报错）
            this.$message.error('获取用户信息失败：' + (error.message || error));
            reject(error);
          });
      });
    },

    // 加载列表数据（若依标准接口请求）
    getList() {
      this.loading = true;
      const params = {
        ...this.queryParams,
        creator: this.currentUser.role === "采购专员" ? this.currentUser.username : undefined,
      };
      listReceipts(params).then((response) => {
        this.tableData = response.rows;
        console.log(response);
        this.total = response.total;
        this.loading = false;
      }).catch((error) => {
        this.$message.error("加载列表失败：" + (error.message || error));
        this.loading = false;
      });
    },

    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    // 重置按钮
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams.operateTimeRange = [];
      this.queryParams.auditTimeRange = [];
      this.handleQuery();
    },


    // 删除按钮（打开弹窗）
    handleDelete(row) {
      this.form = {...row};
      this.title = "删除采购入库单";
      this.openDelete = true;
    },

    // 提交删除（接口请求）
    submitDelete() {
      deleteReceipts(this.form.inboundNo).then((response) => {
        this.$message.success("删除成功");
        this.openDelete = false;
        this.getList();
      });
    },

    // 提交按钮（打开弹窗）
    handleSubmit(row) {
      this.form = {...row};
      this.title = "提交采购入库单";
      this.openSubmit = true;
    },

    // 确认提交（接口请求）
    submitSubmit() {
      submitReceipts(this.form.inboundNo).then((response) => {
        this.$message.success("提交成功");
        this.openSubmit = false;
        this.getList();
      });
    },


    // 处理编辑按钮
    handleEdit(row) {
      this.addOrEditTitle = "修改采购入库单";
      getReceipts(row.inboundNo).then(response => {
        console.log("编辑接口返回数据：", response);
        this.addOrEditForm = response
        console.log(22222, this.addOrEditForm)
        this.openAddOrEdit = true;

      }).catch(error => {
        this.addOrEditForm = {};
        this.$message.error("加载详情失败：" + (error.message || error));
      });
    },

    // 新增：处理查看按钮
    handleView(row) {
      this.title = "查看采购入库单";
      getReceipts(row.inboundNo).then(response => {
        console.log("查看接口返回数据：", response);  // 添加打印
        this.viewForm = response || {};
        this.openView = true;
      }).catch(error => {
        console.error("接口调用失败：", error);
        this.viewForm = {};
        this.$message.error("加载详情失败：" + (error.message || error));
      });
    },
    // 新增：提交新增/修改表单
    submitAddOrEditForm() {
      this.$refs.addOrEditForm.validate(valid => {
        if (valid) {
          // 1. 调试日志：确认使用的API（更新/新增）及入参
          const isUpdate = !!this.addOrEditForm.inboundNo;
          const api = isUpdate ? updateReceipts : addReceipts;
          console.log(`触发${isUpdate ? '更新' : '新增'}操作，入参：`, this.addOrEditForm);

          // 2. API调用（补充错误处理）
          api(this.addOrEditForm)
            .then(() => {
              this.$message.success(`${isUpdate ? '更新' : '新增'}成功`);
              this.openAddOrEdit = false;
              this.getList(); // 刷新列表
            })
            .catch(error => {
              // 3. 错误提示（避免操作失败却显示成功）
              this.$message.error(`${isUpdate ? '更新' : '新增'}失败：${error.message || '网络异常'}`);
            });
        }
      });
    }

  }
};
</script>

<style scoped>
/* 若依标准样式补充 */
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.small-padding .cell {
  padding: 4px 15px;
}

.fixed-width {
  table-layout: fixed;
  width: 100%;
}
</style>
